package com.ruoyi.web.controller.system;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import io.reactivex.Flowable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;


@RestController
@RequestMapping("/tool/api")
public class SysToolController extends BaseController {


    static String key = "";


    /*
     * 调用阿里百炼
     * */
    @PostMapping("/baiLian")
    public static AjaxResult streamCallWithMessage(@RequestBody String command)

            throws NoApiKeyException, ApiException, InputRequiredException {
        Generation gen = new Generation();
        String osName = System.getProperty("os.name").toLowerCase();

        Message userMsg =
                Message.builder().role(Role.USER.getValue()).content(command).build();
        GenerationParam param = GenerationParam.builder()
                .model("qwen-max")
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8).enableSearch(true)
                .incrementalOutput(true)
                .prompt("你是一个终端，根据我的提示给出对应的命令,要确保这个命令能正确运行，可以适当补充参数，不需要解释，当前操作系统是" + osName)
                .apiKey(key)
                .build();

        Flowable<GenerationResult> result = gen.streamCall(param);
        StringBuilder fullContent = new StringBuilder();
        result.blockingForEach(message -> {
            fullContent.append(message.getOutput().getChoices().get(0).getMessage().getContent());
        });
        return AjaxResult.success(fullContent.toString());
    }

}
